//
//  FTextArea3.swift
//  soapp
//
//  Created by zhuxietong on 2021/5/24.
//

import Foundation

import Eelay

open class FTextArea3:FField,UITextViewDelegate{
    public let wordCountL = ASButtonNode()
    public let backNode = MoDisplayNode()

    public let textNode = ASDisplayNode { () -> UIView in
        
    
        let textArea = NextGrowingTextView()
        
        
        textArea.textView.font = .systemFont(ofSize: 14)
        textArea.textView.textAlignment = .left
        textArea.textView.textColor = ._foreground
        textArea.textView.returnKeyType = .done
        return textArea
    }
    
    public var height:CGFloat = 80
   
    deinit {
//        textView.removeObserver(self, forKeyPath: "text")
    }
    
    open func checkWordCount(){

        let max = self.props.num_limit.max
        if max > 100000{
            wordCountL.alpha = 0
            return
        }
        
        let text = textView.textView.text ?? ""

        self.wordCountL.ui.ntitle(title: "\(Int(text.count))/\(max)")
        wordCountL.backgroundColor = UIColor(shex: "#f0f0f0").alpha(0.8)
 
    }

    public var textView:NextGrowingTextView{
        return (textNode.view as? NextGrowingTextView) ?? NextGrowingTextView()
    }
    open override func didLoadProps() {
        textView.textView.text = "\(value)"
       
        lableNode.attributedText = _lable
        textView.textView.attributedPlaceholder = placeholder.ui.font(font: placeHolderStyle.font).color(color: placeHolderStyle.color).left.astring
        checkWordCount()
    }
    
    open override func update(value:Any,edit:FEdit){
        self.value = value
        switch edit {
        case .input:
            break
        case .reply:
            didLoadProps()
            updateDispaly()
        default:
            didLoadProps()
            updateDispaly()
        }
    }
    
    open func changeText(text:String)  {
        self.update(value: text, edit: .input)
    }
    open override func addLayoutRules() {
        super.addLayoutRules()
//        textView.addTextDidChangeHandler {[weak self] (t) in
//            self?.checkWordCount()
//            guard let textF = t else{ return }
//            self?.changeText(text: textF.text ?? "")
////            self?.update(value: textF.text ?? "", edit: .input)
//        }
        wordCountL.ui.ncolor(color: ._weak).font(size: 12).padding(insets: [3,4]).set(radius: 8, width: nil, color: nil)
        backNode.bsui.background(color: ._tableBackground).set(radius: 6, width: TP.separatorHeight, color: ._separator)
    }
  
    open override func willLayoutRules() {
        super.willLayoutRules()
        textView.delegate = self
        textNode.backgroundColor = .clear
        
//        textNode.bsui.background(color: ._tableBackground).set(radius: 3, width: 1, color: UIColor._separator.alpha(0.3))
//        textView.addObserver(self, forKeyPath: "text", options: [.new,.old], context: nil)

    }
    
    open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

//        if text == "\n"{
//            textView.resignFirstResponder()
//            return false
//        }
//        let newStr = textView.text + text
//        if newStr.len > maxWordCount{
//            return false
//        }

        return true

    }
    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        return true
    }
    
    open var maxWordCount:Int{
        return props.num_limit.max
    }
    
    open func textViewDidChange(_ textView: UITextView) {
//
//        if textView.text.count > maxWordCount {
//
//            //获得已输出字数与正输入字母数
//            let selectRange = textView.markedTextRange
//
//            //获取高亮部分 － 如果有联想词则解包成功
//            if let selectRange = selectRange {
//                let position =  textView.position(from: (selectRange.start), offset: 0)
//                if (position != nil) {
//                    return
//                }
//            }
//
//            guard let textContent = textView.text else {
//                return
//            }
//
//            //截取200个字
//            if textContent.len > maxWordCount {
////                let index = textContent.index((textContent.startIndex)!, offsetBy: maxWordCount)
//                let str = textContent.sub(from: 0, end: (maxWordCount - 1))
//                textView.text = str
//            }
//        }
//        update(value: textView.text ?? "", edit: .input)
//
//        checkWordCount()

   }

    
    

//    open override func specGetter() -> _Spec {
//        return .stack(["v|8",&-.stretch,_nowrap], childs: [
//            lableNode.Spec,
//            textNode["\(height)"]
//        ])
//    }
    
    open override func specGetter() -> _Spec {
        let spec = _Spec.inset([], [0], child: .stack(["v|3",&-.stretch], childs: [
            textNode["\(height)"].addOver(.stack(["v",&-.stretch,_justfy(.space_between)], childs: [
                .stack([], childs: []),
                .stack(["h",_justfy(.space_between)], childs: [
                    .stack([], childs: []),
                    _Spec.inset([], [4], child: wordCountL.Spec)
                ])
            ]))
        ])).addBack(backNode.Spec)
        return .stack(["v|8",&-.stretch], childs: [
            .if(label.len > 0, spec: lableNode.Spec),
            spec
        ])
    }
}
